package com.commun;

// import com.alpha.pt.Date;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import maps.test.R;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.PrayTime.PrayTime;
import com.PrayTime.PrayTime.EnumationPrayer;
import com.PrayTime.PrayTimeLayout;
import com.activity.MyMapActivity;
import com.calque.CalqueSites;
import com.calque.CalqueSitesClientTempMosqueAjouter;
import com.calque.CalqueSitesHavePicture;
import com.calque.MyPositionCalque;
import com.compass.Compass;
import com.data.DataBaseQuery;
import com.geo.MyMapView;
import com.google.android.maps.GeoPoint;
import com.object.Mosque;

public class Utils {
	public static List<Mosque> mosquais;
	public static boolean TOAST_TEXT_LAUNCHED = false;
	public static CalqueEnum calqueEnum;
	public static NotificationChoises notificationChoises;
	public static ProgressDialog dialogLoader;

	public enum CalqueEnum {
		HAVE_PICTURE_TEXT, PICTURE_SHOWN, NORMAL, TEMP_ITEMS, MEQUA,

	}

	public enum NotificationChoises {
		DESACTIVER, ACTIVER, ACTIVER_SON, ACTIVER_VIBRATION, ACTIVER_SON_VIBRATION

	}

	public static void RenitialiseMosquesMarqueurs() {
		DataBaseQuery bd = new DataBaseQuery();
		mosquais = bd.getAllMosquaisFromDataBase();
		if (mosquais.isEmpty())
			mosquais = bd.getAllMosquaisFromGoogleAPI();
		else
			mosquais.addAll(bd.getAllMosquaisFromGoogleAPI());

	}

	public static List<Mosque> getMosquais() {

		return mosquais;
	}

	public static void setMosquais(List<Mosque> mosquai) {
		mosquais = mosquai;
	}

	public static double deg2rad(final double deg) {
		return deg * Math.PI / 180;
	}

	public static float rad2deg(final double rad) {
		return (float) (rad * 180 / Math.PI);
	}

	public static Integer str2int(final String str, final int defaut) {
		return str.matches("[0-9\\-]+") ? Integer.parseInt(str) : defaut;
	}

	public static String int2str(final Integer val) {
		return ((val < 10) ? "0" : "") + Integer.toString(val);
	}


	public static boolean geoPointsAreSame(GeoPoint newMapCenter,
			GeoPoint oldMapCenter) {
		if (newMapCenter.getLatitudeE6() == oldMapCenter.getLatitudeE6()) {
			if (newMapCenter.getLongitudeE6() == oldMapCenter.getLongitudeE6()) {
				return true;
			}
		}
		return false;
	}

	public static Toast getMyCustomTextToast(Context context, String text) {

		LayoutInflater inflater = ((Activity) context).getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
				(ViewGroup) ((Activity) context)
						.findViewById(R.id.toast_layout_root));

		layout.setBackgroundDrawable(((Activity) context).getResources()
				.getDrawable(R.drawable.toast_layout_bg));
		TextView texts = (TextView) layout.findViewById(R.id.text);
		texts.setText(text);
		Toast toast = new Toast(((Activity) context).getApplicationContext());
		toast.setGravity(Gravity.CENTER, 0, 80);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);

		return toast;
	}

	public static Toast getMyCustomImageShowToast(Context context, int resID) {
		Toast toast = new Toast(((Activity) context).getApplicationContext());
		toast.setGravity(Gravity.CENTER, 0, 0);
		LayoutInflater inflater = ((Activity) context).getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_picture_layout,
				(ViewGroup) ((Activity) context)
						.findViewById(R.id.toast_picture));
		ImageView imgView = (ImageView) layout
				.findViewById(R.id.image_mosque_view);
		imgView.setImageResource(resID);
		toast.setDuration(Toast.LENGTH_SHORT);

		toast.setView(layout);

		return toast;
	}

	public static MyMapView MapMarqueurSetup(MyMapView myMapView,
			Context context) {

		// calque normal sans image
		Drawable marqueur = ((Activity) context).getResources().getDrawable(
				R.drawable.brun_mosque);

		marqueur.setBounds(0, 0, marqueur.getIntrinsicWidth(),
				marqueur.getIntrinsicHeight());

		CalqueSites.InitialisationInsatance(marqueur, context, myMapView);
		myMapView.getOverlays().add(CalqueSites.getInstance());

		// calque avec image
		Drawable marqueurMosqueImage = ((Activity) context).getResources()
				.getDrawable(R.drawable.brun_mosque_image);

		marqueur.setBounds(0, 0, marqueurMosqueImage.getIntrinsicWidth(),
				marqueurMosqueImage.getIntrinsicHeight());
		CalqueSitesHavePicture.InitialisationInsatance(marqueurMosqueImage,
				context, myMapView);
		myMapView.getOverlays().add(CalqueSitesHavePicture.getInstance());

		// myCalquePosition
		Drawable marqueurMyPosition = ((Activity) context).getResources()
				.getDrawable(R.drawable.circle_blue);
		marqueurMyPosition.setBounds(0, 0,
				marqueurMyPosition.getIntrinsicWidth(),
				marqueurMyPosition.getIntrinsicHeight());

		myMapView.getOverlays().add(
				new MyPositionCalque(marqueurMyPosition, context));

		// le mosquer ajouter par le client
		Drawable marqueurTempClientMosquee = ((Activity) context)
				.getResources().getDrawable(R.drawable.blue_tag);

		marqueurTempClientMosquee.setBounds(0, 0,
				marqueurTempClientMosquee.getIntrinsicWidth(),
				marqueurTempClientMosquee.getIntrinsicHeight());
		CalqueSitesClientTempMosqueAjouter.InitialisationInsatance(
				marqueurTempClientMosquee, context, myMapView);
		myMapView.getOverlays().add(
				CalqueSitesClientTempMosqueAjouter.getInstance());

		return myMapView;
	}

	public static TabHost setupTabHost(final TabHost tabHost,
			final Context context) {

		tabHost.setup();

		tabHost.addTab(tabHost
				.newTabSpec("OngletSalatTime")
				.setIndicator(
						"",
						((Activity) context).getResources().getDrawable(
								R.drawable.ic_tab_clock))
				.setContent(R.id.OngletSalatTime));

		tabHost.addTab(tabHost
				.newTabSpec("OngletMap")
				.setIndicator(
						"",
						((Activity) context).getResources().getDrawable(
								R.drawable.ic_tab_location))
				.setContent(R.id.OngletMap));
		tabHost.addTab(tabHost
				.newTabSpec("OngletBoussole")
				.setIndicator(
						"",
						((Activity) context).getResources().getDrawable(
								R.drawable.ic_tab_compass))
				.setContent(R.id.OngletBoussole));
		tabHost.addTab(tabHost
				.newTabSpec("OngletSetting")
				.setIndicator(
						"",
						((Activity) context).getResources().getDrawable(
								R.drawable.ic_tab_setting))
				.setContent(R.id.OngletSetting));
		LinearLayout boussoleLinearLayout = (LinearLayout) ((Activity) context)
				.findViewById(R.id.OngletBoussole);

		boussoleLinearLayout.addView(new Compass(context));

		RelativeLayout prayTimeLayout = (RelativeLayout) ((Activity) context)
				.findViewById(R.id.OngletSalatTime);
		prayTimeLayout.addView(new PrayTimeLayout(context));

		for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
			tabHost.getTabWidget().getChildAt(i)
					.setBackgroundColor(Color.parseColor("#808080"));

		}

		tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
				.setBackgroundColor(Color.parseColor("#ffcccccc"));

		tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
			public void onTabChanged(String tabId) {

				for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
					tabHost.getTabWidget().getChildAt(i)
							.setBackgroundColor(Color.parseColor("#808080"));
				}
				tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
						.setBackgroundColor(Color.parseColor("#ffcccccc"));

				dismissToasts(context);

				if (tabHost.getCurrentTab() == 1 && DataBaseQuery.rayonChanged) {

					if (MyMapActivity.isNetworkConnected) {
						Double rayonState = Double
								.parseDouble(PreferenceManager
										.getDefaultSharedPreferences(
												MyMapActivity.getmContext())
										.getString(Param.RAYON, "5"));
						if (DataBaseQuery.rayon != rayonState
								|| DataBaseQuery.firstResumeForMosquePosition) {
							DataBaseQuery.firstResumeForMosquePosition = false;
							final ProgressDialog dialogLoader = ProgressDialog.show(
									context, "",
									context.getString(R.string.loading), true);
							dialogLoader.show();

							DataBaseQuery.rayon = rayonState;
							Handler mHandler = new Handler();
							Runnable mUpdateTimeTask = new Runnable() {
								public void run() {
									
									Utils.RenitialiseMosquesMarqueurs();
									CalqueSites.getInstance().Renitialise();
									CalqueSitesHavePicture.getInstance()
											.Renitialise();
									DataBaseQuery.rayonChanged = false;
									dialogLoader.dismiss();
									
									Utils.TOAST_TEXT_LAUNCHED = false;
								}
							};
							mHandler.removeCallbacks(mUpdateTimeTask);
							mHandler.postDelayed(mUpdateTimeTask, 2000);

						} 
					} else {
						String error = context
								.getString(R.string.dialog_error_connection_fail);
						Toast.makeText(MyMapActivity.getmContext(), error,
								Toast.LENGTH_LONG).show();
					}
				}

			}
		});

		return tabHost;
	}

	public static void DelayTimer(final Context context, int time) {

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {
				GetCutomize_layout_toast_outer_layout(context).setVisibility(
						View.VISIBLE);

				Utils.TOAST_TEXT_LAUNCHED = true;

			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, time);
	}

	public static RelativeLayout GetCutomize_layout_toast_outer_layout(
			final Context context) {
		return (RelativeLayout) ((Activity) context)
				.findViewById(R.id.cutomize_layout_toast_outer_layout);
	}

	public static RelativeLayout GetItem_update_layout(final Context context) {
		return (RelativeLayout) ((Activity) context)
				.findViewById(R.id.item_update_layout);
	}

	public final static int TIME_DELAYING = 200;

	public static void DisparitonLayoutImageTaost(final Context context) {

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {

				GetCutomize_layout_toast_outer_layout(context).setVisibility(
						View.INVISIBLE);
				// GetCutomize_layout_toast_outer_layout(context).setAlpha(1.0F);//2.2

				Utils.TOAST_TEXT_LAUNCHED = false;
			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, TIME_DELAYING);
	}

	public static void DisparitonLayoutTempItemTaost(final Context context) {

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {

				GetItem_update_layout(context).setVisibility(View.INVISIBLE);
				// GetItem_update_layout(context).setAlpha(1.0F); //2.2

				Utils.TOAST_TEXT_LAUNCHED = false;
			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, TIME_DELAYING);
	}

	public static void MyCustomisedViewToast(final Context context,
			final String text, final int resID) {

		RelativeLayout relativeLayout = Utils
				.GetCutomize_layout_toast_outer_layout(context);

		TextView texts = (TextView) relativeLayout
				.findViewById(R.id.cutomize_layout_toast_text);
		// texts = getArabicEnabledTextView(context, texts);
		texts.setText("   " + text + "  ");

		ImageButton imageButton = (ImageButton) relativeLayout
				.findViewById(R.id.cutomize_layout_toast_image);

		if (resID != -1) {

			imageButton.setImageResource(R.drawable.toast_image_botton);

			imageButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Utils.calqueEnum = CalqueEnum.PICTURE_SHOWN;

					CalqueSitesHavePicture.myToast = Utils
							.getMyCustomImageShowToast(context, resID);
					CalqueSitesHavePicture.myToast.show();

					Utils.GetCutomize_layout_toast_outer_layout(context)
							.setVisibility(View.INVISIBLE);
					Utils.TOAST_TEXT_LAUNCHED = true;

				}
			});

		} else {
			imageButton.setImageResource(R.drawable.transparent);

		}

		Handler mHandler = new Handler();
		Runnable mUpdateTimeTask = new Runnable() {
			public void run() {
				GetCutomize_layout_toast_outer_layout(context).setVisibility(
						View.VISIBLE);
				Utils.calqueEnum = CalqueEnum.HAVE_PICTURE_TEXT;

				Utils.TOAST_TEXT_LAUNCHED = true;

			}
		};
		mHandler.removeCallbacks(mUpdateTimeTask);

		mHandler.postDelayed(mUpdateTimeTask, TIME_DELAYING);

	}

	// #######
	public static void dismissToasts(Context mContext) {
		if (Utils.TOAST_TEXT_LAUNCHED) {
			switch (Utils.calqueEnum) {
			case NORMAL:
				Utils.DisparitonLayoutImageTaost(mContext);
				break;
			case TEMP_ITEMS:
				Utils.DisparitonLayoutTempItemTaost(mContext);
				break;
			case HAVE_PICTURE_TEXT:
				Utils.DisparitonLayoutImageTaost(mContext);
				break;
			case PICTURE_SHOWN:
				Utils.DisparitonLayoutImageTaost(mContext);

				CalqueSitesHavePicture.myToast.cancel();
				break;
			}
		}

	}

	public static String GetUniquePhoneID() {
		final TelephonyManager tm = (TelephonyManager) MyMapActivity
				.getmContext().getSystemService(Context.TELEPHONY_SERVICE);

		final String tmDevice, tmSerial, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = ""
				+ android.provider.Settings.Secure.getString(MyMapActivity
						.getmContext().getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);

		UUID deviceUuid = new UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
		return deviceUuid.toString();

	}

	public static void AlertTestDeveloppementMsg(String text) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				MyMapActivity.getmContext());

		builder.setMessage(text)
				.setCancelable(false)
				.setPositiveButton(R.string.oui,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						})
				.setNegativeButton(R.string.non,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private static final String FONTS_LOCATION_PATH = "fonts/DejaVuSans.ttf";

	public static TextView getArabicEnabledTextView(Context context,
			TextView targetTextView) {
		// this is a static for testing!
		Typeface face = Typeface.createFromAsset(context.getAssets(),
				FONTS_LOCATION_PATH);
		targetTextView.setTypeface(face);

		return targetTextView;
	}

	public static EnumationPrayer ChekPrayTime() {

		ArrayList<String> prayTime = PrayTime.getInstance()
				.GetPrayTimeStringsCustom(
						PreferenceManager.getDefaultSharedPreferences(
								MyMapActivity.getmContext()).getInt(
								"pray_time_cal_meth", 0));
		Date now = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(now);
		
		int houre = cal.get(Calendar.HOUR_OF_DAY);
		int minuts = cal.get(Calendar.MINUTE);

		String fajr = prayTime.get(0).trim();
		String dhohr = prayTime.get(2).trim();
		String asr = prayTime.get(3).trim(); 
		String maghreb = prayTime.get(4).trim();
		String isha = prayTime.get(6).trim();

		if ((Integer.parseInt(fajr.substring(0, 2)) == houre)
				&& (Integer.parseInt(fajr.substring(3, 5)) == minuts))
			return EnumationPrayer.FAJR;
		if ((Integer.parseInt(dhohr.substring(0, 2)) == houre)
				&& (Integer.parseInt(dhohr.substring(3, 5)) == minuts))
			return EnumationPrayer.DHOHR;
		if ((Integer.parseInt(asr.substring(0, 2)) == houre)
				&& (Integer.parseInt(asr.substring(3, 5)) == minuts))
			return EnumationPrayer.ASR;
		if ((Integer.parseInt(maghreb.substring(0, 2)) == houre)
				&& (Integer.parseInt(maghreb.substring(3, 5)) == minuts))
			return EnumationPrayer.MAGHREB;
		if ((Integer.parseInt(isha.substring(0, 2)) == houre)
				&& (Integer.parseInt(isha.substring(3, 5)) == minuts))
			return EnumationPrayer.ISHA;

		return EnumationPrayer.NO_ONE;
	} 

//	public static boolean IsNetworkConnected(Context context) {
//		 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//		    // test for connection
//		    if (cm.getActiveNetworkInfo() != null
//		            && cm.getActiveNetworkInfo().isAvailable()
//		            && cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
//		        return true;
//		    } else {
//		        return false;
//		    }
//	}
	public static void isNetworkAvailable(final Handler handler, final int timeout) {

        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

        new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)

                new Thread() {

                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet("http://m.google.com");
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                        } catch (Exception e) {}
                    }

                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) { 
                            waited += 100;
                        }
                    }
                } 
                catch(InterruptedException e) {} // do nothing 
                finally { 
                    if (!responded) { handler.sendEmptyMessage(0); } 
                    else { handler.sendEmptyMessage(1); }
                }

            }

        }.start();

}

	enum Language {
		ARABE, FRANCAIS, ANGLAIS
	}
}